package com.yulebaby.callsenter.http;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.ui.activity.LoginActivity;
import com.yulebaby.callsenter.utils.SPUtil;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.json.JSONObject;

import okhttp3.Call;
//import okhttp3.Response;

/**
 * Author: Zhangbo
 * Time: 2016/11/8
 */
public class HttpHelper {
    private static final long DEFAULT_MILLISECONDS = 20000; //请求超时时间 20秒
    private static HttpHelper httpHelper = new HttpHelper();
    private static final String CODE = "code";
    private static final String RESULT = "result";
    private static final String INFO = "info";

    public static HttpHelper getInstance() {
        return httpHelper;
    }

    /**
     * 异步get请求
     *
     * @param url
     */
    public void get(final Activity activity, String url, HttpParams params, final HttpCallback callback) {
        OkGo.get(url)     // 请求方式和请求url
                .tag(activity)
                .cacheKey("get")
                .params(params)
//                .execute(new StringCallback());
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        HttpHelper.this.handleResponse(activity, s, callback);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        callback.onFail(e.getLocalizedMessage());
                    }
                });
    }

    /**
     * 异步Post请求,
     *
     * @param activity
     * @param url
     * @param params
     * @param callback
     */
    public void post(final Activity activity, String url, HttpParams params, final HttpCallback callback) {
        OkGo.post(url)
                .tag(activity)
                .params(params)
                .cacheKey("post")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        HttpHelper.this.handleResponse(activity, s, callback);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        callback.onFail(e.getLocalizedMessage());
                    }
                });
    }

    /**
     * 异步Post请求,
     *
     * @param activity
     * @param url
     * @param params
     * @param callback
     */
    public void postJson(final Activity activity, String url, HttpParams params, final HttpCallback callback) {
        OkGo.post(url)
                .tag(activity)
                .params(params)
                .cacheKey("post")
                .upJson("sss")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        HttpHelper.this.handleResponse(activity, s, callback);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        callback.onFail(e.getLocalizedMessage());
                    }
                });
    }


    /**
     * 上传单个文件
     *
     * @param url
     * @param params
     * @param callback
     */
    public void postFile(String url, HttpParams params, final HttpCallback callback) {
        OkGo.post(url)
                .params(params)
                .cacheKey("files")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        HttpHelper.this.handleResponse(null, s, callback);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        callback.onFail(e.getLocalizedMessage());
                    }
                });
    }


    public static void init(Application application) {
        OkGo.init(application);
        try {
            OkGo.getInstance()
                    .debug("yulebaby")
                    .setConnectTimeout(DEFAULT_MILLISECONDS)
                    .setReadTimeOut(DEFAULT_MILLISECONDS)
                    .setWriteTimeOut(DEFAULT_MILLISECONDS)
                    .setCacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                    .setCookieStore(new PersistentCookieStore());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消请求
     *
     * @param activity
     */
    public void cancel(Activity activity) {
        OkGo.getInstance().cancelTag(activity);
    }

    /**
     * 处理请求结果
     *
     * @param activity
     * @param json
     * @param callBack
     */
    private void handleResponse(Activity activity, String json, HttpCallback callBack) {
        try {
            //转化为json对象
            JSONObject jsonObject = new JSONObject(json);
            //判断CODE字段是否存在，不存在返回失败信息并结束请求
            if (jsonObject.isNull(CODE)) {
                callBack.onFail("error key not exists!!");
                return;
            }
            String codeResult = jsonObject.getString(CODE);
            String info = jsonObject.getString(INFO);
            switch (codeResult) {
                case HttpCallBackCode.ERR_PARAM:
                    showToast(info);
                    callBack.onFailParam(info);
                    return;
                case HttpCallBackCode.ERR_SYSTEM:
                    showToast(info);
                    return;
                case HttpCallBackCode.ERR_TOKEN:
                    showToast(info);
                    //TOKEN 失效跳转到登录界面
                    SPUtil.remove(Constant.USER_TOKEN); //对登录信息进行清除
                    SPUtil.remove(Constant.USER_ID);
                    if (activity != null) {
                        activity.startActivity(new Intent(activity, LoginActivity.class));
                        activity.finish();
                    }
                    return;
            }
            //判断RESULT字段是否存在，不存在返回时报回调并结束请求
            if (jsonObject.isNull(RESULT)) {
                callBack.onSuccessResultNull();
                return;
            }
            //获取results的值
            String results = jsonObject.getString(RESULT);
            //返回成功回调
            callBack.onSuccess(new Gson().fromJson(results, callBack.type));
        } catch (Exception e) {
            callBack.onFail(e.getLocalizedMessage());
        }
    }

    /**
     * Toast
     *
     * @param info
     */
    private void showToast(String info) {
        if (!TextUtils.isEmpty(info)) {
            ToastUtil.showToast(info);
        }
    }

}
